from django.db import models

# From NoPBX
from nopbx.core.models import BaseModule
from nopbx.dialplan.models import Context

###############################################################################

class NetworkManager(models.Manager):
    def get_by_natural_key(self, network, netmask):
        return self.get(network = network, netmask = netmask)

class Network(BaseModule):
    """
    Logical network information
    """
    NETMASK_CHOICES = (
        (8,  '/8  (255.0.0.0)'),
        (9,  '/9  (255.128.0.0)'),
        (10, '/10 (255.192.0.0)'),
        (11, '/11 (255.224.0.0)'),
        (12, '/12 (255.240.0.0)'),
        (13, '/13 (255.248.0.0)'),
        (14, '/14 (255.252.0.0)'),
        (15, '/15 (255.254.0.0)'),
        (16, '/16 (255.255.0.0)'),
        (17, '/17 (255.255.128.0)'),
        (18, '/18 (255.255.192.0)'),
        (19, '/19 (255.255.224.0)'),
        (20, '/20 (255.255.240.0)'),
        (21, '/21 (255.255.248.0)'),
        (22, '/22 (255.255.252.0)'),
        (23, '/23 (255.255.254.0)'),
        (24, '/24 (255.255.255.0)'),
        (25, '/25 (255.255.255.128)'),
        (26, '/26 (255.255.255.192)'),
        (27, '/27 (255.255.255.224)'),
        (28, '/28 (255.255.255.240)'),
        (29, '/29 (255.255.255.248)'),
        (30, '/30 (255.255.255.252)'),
        (32, '/32 (255.255.255.255)'),
    )

    name    = models.CharField(max_length = 50, unique = True)
    network = models.IPAddressField()
    netmask = models.PositiveSmallIntegerField(default = '24', choices = NETMASK_CHOICES)

    class Meta:
        ordering = ['network', 'netmask']
        unique_together = ['network', 'netmask']

    def cidr(self):
        return '%s/%d' % (self.network, self.netmask)
    cidr.short_description = 'Network (CIDR Notation)'

    def __unicode__(self):
        return '%s (%s/%d)' % (self.name, self.network, self.netmask)

    def natural_key(self):
        return (self.network, self.netmask)



###############################################################################

class LocationManager(models.Manager):
    def get_by_natural_key(self, name):
        return self.get(name = name)

class Location(BaseModule):
    """
    Physical location information
    """
    name    = models.CharField(max_length = 50, unique = True)
    context = models.ForeignKey(Context, limit_choices_to = {'context_type':2})
    network = models.ForeignKey(Network, blank = True, null = True)

    objects = LocationManager()
    class Meta:
        ordering = ['name']


    def __unicode__(self):
        return self.name

    def natural_key(self):
        return self.name

